﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Configuration;
using System.IO;
using System.Xml.Serialization;

namespace IKEA.FileExchange.Configuration
{
    [Serializable]
    public class FileExchangeConfiguration
    {
        private const string AppSettingKey = "IKEA.FileExchange.ConfigurationFilePath";
        private static XmlSerializer serializer = new XmlSerializer(typeof(FileExchangeConfiguration));

        public static FileExchangeConfiguration LoadConfiguration()
        {
            string filePath = ConfigurationManager.AppSettings[AppSettingKey];

            using (FileStream fs = new FileStream(filePath, FileMode.Open))
            {
                FileExchangeConfiguration config = (FileExchangeConfiguration) serializer.Deserialize(fs);
                return config;
            }
        }

        private List<IPAddressAuthenticationRule> authenticationRules;
        private List<FileExchangeUserInfo> users;

        public List<FileExchangeUserInfo> Users
        {
            get
            {
                return users;
            }
            set
            {
                users = value;
            }
        }

        public List<IPAddressAuthenticationRule> AuthenticationRules
        {
            get
            {
                return authenticationRules;
            }
            set
            {
                authenticationRules = value;
            }
        }

        public IPAddressAuthenticationRule FindRule(string keyword)
        {
            foreach (IPAddressAuthenticationRule rule in AuthenticationRules)
            {
                if (rule.IPAddress.ToLower() == keyword.ToLower())
                {
                    return rule;
                }
            }

            return null;
        }

        public FileExchangeUserInfo GetUser(string userName)
        {
            foreach (FileExchangeUserInfo userInfo in Users)
            {
                if (userInfo.Name.ToLower() == userName.ToLower())
                {
                    return userInfo;
                }
            }

            return null;
        }

        public FileExchangeConfiguration()
        {
            users = new List<FileExchangeUserInfo>();
            authenticationRules = new List<IPAddressAuthenticationRule>();
        }
    }
}
